package com.wyz.demo;

/**
 *  这个是使用jdk自带的InheritableThreadLocal 解决子线程无法访问父线程的ThreadLocal变量的问题，在线程池中无效
 */
public class InheritableThreadLocalExample {
    private static final InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();

    public static void main(String[] args) {
        inheritableThreadLocal.set("Parent Thread Value");

        // 创建子线程
        Thread childThread = new Thread(() -> {
            // 子线程可以直接获取父线程的 ThreadLocal 值
            System.out.println("Child Thread: " + inheritableThreadLocal.get());
        });

        childThread.start();

        try {
            childThread.join(); // 等待子线程执行完毕
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Parent Thread: " + inheritableThreadLocal.get());
    }
}